package com.novabluetooth.services.service;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.health.tablebean.BTDevice;
import com.health.viewscontrols.NovaApplication;
import com.nova.view.BaseSharedPreferencesUtil;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.services.bean.BluetoothLeDevice;
import com.novabluetooth.services.constant.BluetoolUtil;

import java.util.List;


/**
 * 作者: JiangYL
 * 作用: 蓝牙扫描类，系统5.0及其以上系统
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class BluetoothLeScanner5 extends BluetoothLeScannerInterface {
    private final Handler mHandler;
    private final BluetoothUtils mBluetoothUtils;
    private final Handler notifyHandler; //界面通知handler
    private boolean mScanning;
    private BluetoothLeScanner scanner;

    public BluetoothLeScanner5(Handler nHandler, BluetoothUtils bluetoothUtils){
        mHandler = new Handler();
        mBluetoothUtils = bluetoothUtils;
        notifyHandler = nHandler;
    }

    public boolean isScanning() {
        return mScanning;
    }

    @Override
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void scanLeDevice(final int duration, final boolean enable) {
        if (enable) {
            if(mScanning){return;}
            Log.d("TAG", "~ Starting Scan");
            // Stops scanning after a pre-defined scan period.
            if(duration > 0){
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("TAG", "~ Stopping Scan (timeout)");
                        mScanning = false;
                        if (mBluetoothUtils != null){
                            if (mLeScanCallback != null){
                                mBluetoothUtils.getBluetoothAdapter().getBluetoothLeScanner().stopScan(mLeScanCallback);
                            }
                        }
                    }
                }, duration);
            }

            mScanning = true;
            if (mLeScanCallback != null){
                mBluetoothUtils.getBluetoothAdapter().getBluetoothLeScanner().startScan(mLeScanCallback);
            } else {
                Log.e("TAG", "LeScanCallback is Can not be empty");
            }
        } else {
            Log.e("TAG", "~ Stopping Scan");
            mScanning = false;
            if (mLeScanCallback != null){
                mBluetoothUtils.getBluetoothAdapter().getBluetoothLeScanner().stopScan(mLeScanCallback);
            }
        }
    }

    private ScanCallback  mLeScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();
            if (!TextUtils.isEmpty(device.getName())) {
                if (BluetoothConstant.TIZHONG_HEALTH.equals(device.getName())) {
                    List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                            "macAddress = " + "'" + device.getAddress() + "'");
                    if(null!=device&&btDevices.size()>0){
                        String  deviceName = device.getName();
                        if(TextUtils.isEmpty(deviceName) && null!=result.getScanRecord()){
                            deviceName = result.getScanRecord().getDeviceName();
                        }
                        Log.e("BluetoothLeScanner5","发现BLE称=" + deviceName + "[" + device.getAddress() + "]");
                        if (device != null && deviceName != null) {
                            Log.i("BluetoothLeScanner5","发现BLE称=" + deviceName + "[" + device.getAddress() + "]");
                            /* 停止蓝牙扫描 */
                            if (mScanning && mBluetoothUtils != null) {
                                if (mLeScanCallback != null){
                                    mBluetoothUtils.getBluetoothAdapter().getBluetoothLeScanner().stopScan(mLeScanCallback);
                                }
                                mScanning = false;
                            }
                            final BluetoothLeDevice deviceLe = new BluetoothLeDevice(result.getDevice(), result.getRssi(), null==result.getScanRecord()?null:result.getScanRecord().getBytes(), System.currentTimeMillis());
                            //通知发现蓝牙了
                            if(null != notifyHandler){
                                Message msg1 = mHandler.obtainMessage(BluetoolUtil.FOUND_DEVICE);
                                msg1.obj = deviceLe;
                                notifyHandler.sendMessage(msg1);
                            }
                        }
                    }
                }else{
                    return;
                }
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            //Log.e("搜索失败");
        }
    };
}
